/**
  * @Author: songgh
  * @Date: 2021-09-20 14:41:08
  * @LastEditors: songgh
  * @LastEditTime: 2021-09-20 15:41:08
  * @Description: 登录
  */
import { defineComponent, ref } from "vue";
import { getPublickey, ILoginData, rsaLogin } from "@src/api";
import { useRouter } from "vue-router";
import { Toast } from "vant";
import { useStore } from "vuex";
import JsEncrypt from "jsencrypt";

export default defineComponent({
    name: "Login",
    setup() {
        let loginName = ref<string>("hzadmin");
        let loginPwd = ref<string>("pass123");

        const router = useRouter();
        const store = useStore();

        const onSubmit = async (values: ILoginData) => {
            const { loginName, loginPwd } = values;
            Toast.loading({ message: "正在登录", forbidClick: true });

            try {
                const publicKey = await getPublickey();
                const rsa = new JsEncrypt();
                rsa.setPublicKey(`${publicKey}`);

                const data = await rsaLogin({ loginName, loginPwd: rsa.encrypt(loginPwd) as string });
                store.dispatch("user/setUserInfo", data);
                router.push("/home");
            } catch (error) {
                console.error(error);
            }
        };

        return {
            onSubmit,
            loginName,
            loginPwd,
        };
    },
    render() {
        return (
            <div class="h-screen flex flex-col items-center justify-center">
                <h1 class="text-5xl mb-20 text-center">责任规划师</h1>
                <div>
                    <van-form onSubmit={this.onSubmit} >
                        <van-field
                            v-model:modelValue={this.loginName}
                            name="loginName"
                            label="用户名"
                            placeholder="用户名"
                            rules={[{ required: true, message: "请填写用户名" }]}
                        />
                        <van-field
                            v-model:modelValue={this.loginPwd}
                            type="password"
                            name="loginPwd"
                            label="密码"
                            placeholder="密码"
                            rules={[{ required: true, message: "请填写密码" }]}
                        />
                        <div class="my-6 mx-3">
                            <van-button round block type="primary" native-type="submit">
                                登录
                            </van-button>
                        </div>
                    </van-form>
                </div>
            </div>
        );
    },
});
